package middleware

import (
	"advertising/config"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	conf := cors.DefaultConfig()

	conf.AllowOriginFunc = func(origin string) bool {
		if len(config.Config.Cors.AllowOrigins) <= 0 {
			return true
		} else {
			for _, _origin := range config.Config.Cors.AllowOrigins {
				if _origin == origin {
					return true
				}
			}
		}
		return false
	}

	conf.AddAllowMethods(config.Config.Cors.AllowMethods...)
	conf.AddAllowHeaders(config.Config.Cors.AllowHeaders...)
	conf.AllowCredentials = true
	return cors.New(conf)
}
